package cn.tedu.csmall.product.controller;


import cn.tedu.csmall.product.pojo.param.AttributeAddNewParam;
import cn.tedu.csmall.product.pojo.vo.AttributeListItemVO;
import cn.tedu.csmall.product.service.IAttributeService;
import com.example.csmall.commons.pojo.vo.PageData;
import com.example.csmall.commons.web.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 处理属性相关请求的控制器
 *
 * @author java@tedu.cn
 * @version 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/attribute")
@Validated
@Api(tags = "09. 属性管理模块")
public class AttributeController {
    @Autowired
    private IAttributeService attributeService;

    // http://localhost:9180/attribute/add-new
    @PostMapping("/add-new")
    @PreAuthorize("hasAuthority('/pms/product/add-new')")
    @ApiOperation("添加属性")
    @ApiOperationSupport(order = 100)
    public JsonResult<Void> addNew(@Valid AttributeAddNewParam attributeAddNewParam) {
        log.debug("开始处理【添加属性】的请求，参数：{}", attributeAddNewParam);
        attributeService.addNew(attributeAddNewParam);
        return JsonResult.ok();
    }

    // http://localhost:9180/attribute/list-by-template
    @GetMapping("/list-by-template")
    @PreAuthorize("hasAuthority('/pms/product/read')")
    @ApiOperation("根据属性模板查询属性列表")
    @ApiOperationSupport(order = 410)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "templateId", value = "属性模板ID", required = true, paramType = "query", dataType = "long"),
            @ApiImplicitParam(name = "page", value = "页码", paramType = "query"),
            @ApiImplicitParam(name = "queryType", value = "查询类型", example = "all")
    })
    public JsonResult listBy(Long templateId, @Range(min = 1, message = "查询相册列表失败，请提供正确的页码值！")Integer page, String queryType) {
        log.debug("开始处理【根据属性模板ID查询属性列表】的请求，属性模板ID：{}，页码：{}", templateId, page);
        Integer pageNum = page == null ? 1 : page;
        PageData<AttributeListItemVO> pageData;
        if ("all".equals(queryType)) {
            pageData = attributeService.listByTemplateId(templateId, pageNum, Integer.MAX_VALUE);
        } else {
            pageData = attributeService.listByTemplateId(templateId, pageNum);
        }
        return JsonResult.ok(pageData);
    }
}
